# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        prev_node = None
        prev_acc = 0
        cur_acc = 0
        node = head

        node_cnt = 0
        while node:
            node_cnt += 1
            node = node.next

        if node_cnt == 0:
            return head

        k = k % node_cnt

        new_tail = None
        node = head
        while node:
            gap = cur_acc - prev_acc
            if gap == k:
                prev_acc += 1
                if not prev_node:
                    prev_node = head
                else:
                    prev_node = prev_node.next

            cur_acc += 1
            if not node.next:
                new_tail = node

            node = node.next
            if gap < k and not node:
                node = head

        if prev_node and prev_node.next:
            cut_node = prev_node.next
            prev_node.next = None
            new_tail.next = head
            return cut_node

        return head

